package com.jasonjan.jiance.module.me;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.jasonjan.jiance.R;
import com.jasonjan.jiance.api.ILoginApi;
import com.jasonjan.jiance.bean.ModifyPasswordBean;
import com.jasonjan.jiance.global.Constant;
import com.jasonjan.jiance.global.ErrorAction;
import com.jasonjan.jiance.global.InitApp;
import com.jasonjan.jiance.global.RetrofitFactory;
import com.jasonjan.jiance.module.base.BaseActivity;
import com.jasonjan.jiance.util.MD5Util;
import com.jasonjan.jiance.util.T;

import org.json.JSONException;
import org.json.JSONObject;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class ModifyActivity extends BaseActivity {

    private static final String TAG = "ModifyActivity";
    private String flag="";
    private EditText oldPassword_et;
    private EditText newPassword1_et;
    private EditText newPassword2_et;
    private Button modify_btn;

    private String newPassword1;
    private String newPassword2;
    private String oldPassword;

    public static void launch(String flag) {
        InitApp.AppContext.startActivity(new Intent(InitApp.AppContext, ModifyActivity.class)
                .putExtra("flag",flag)
                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_modify);
        setTitle("修改密码");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        flag=getIntent().getStringExtra("flag");
        initView();
        initData();

    }

    private void initView(){
        oldPassword_et=(EditText) findViewById(R.id.oldPassword_et);
        newPassword1_et=(EditText) findViewById(R.id.newPassword1_et);
        newPassword2_et=(EditText) findViewById(R.id.newPassword2_et);
        modify_btn=(Button) findViewById(R.id.modify_btn);
    }

    private void initData(){
        modify_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                newPassword1=(newPassword1_et.getText()==null?"":newPassword1_et.getText().toString().trim());
                newPassword2=(newPassword2_et.getText()==null?"":newPassword2_et.getText().toString().trim());
                oldPassword=(oldPassword_et.getText()==null?"":oldPassword_et.getText().toString().trim());
                if(oldPassword.equals("")){
                    T.showShort("原密码不为空！");
                } else if(newPassword1.length()<6||newPassword1.length()>16){
                    T.showShort("新密码长度只能取6-16位！");
                }else if(!newPassword1.equals(newPassword2)){
                    T.showShort("确认密码不匹配！");
                }else{
                    doRequest(newPassword1,oldPassword);
                }
            }
        });

    }

    private void doRequest(String newPwd,String oldPwd){
        //构造请求参数
        JSONObject requestJson=new JSONObject();
        try{
            SharedPreferences user_info=getSharedPreferences("user_info",Context.MODE_PRIVATE);
            String token=user_info.getString("token","");
            requestJson.put("newPwd",newPwd);
            requestJson.put("oldPwd", oldPwd);
            requestJson.put("sign", MD5Util.md5(Constant.salt+token));
        }catch (JSONException e){
            e.printStackTrace();
        }
        RequestBody body= RequestBody.create(MediaType.parse(Constant.Content_Type),requestJson.toString());
        RetrofitFactory.getRetrofit().create(ILoginApi.class).getAlterPassword(body)
                .subscribeOn(Schedulers.io())
                .switchMap(new Function<ModifyPasswordBean, Observable<ModifyPasswordBean>>() {
                    @Override
                    public Observable<ModifyPasswordBean> apply(@NonNull ModifyPasswordBean modifyPasswordBean) throws Exception {

                        ModifyPasswordBean data = modifyPasswordBean;
                        Log.d("login","data获取数据为："+data.toString());
                        return Observable.just(data);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ModifyPasswordBean>() {
                    @Override
                    public void accept(@NonNull ModifyPasswordBean modifyPasswordBean) throws Exception {
                        if(modifyPasswordBean.getCode().equals("200")){
                            T.showShort("修改成功！");
                            finish();
                        }else{
                            T.showShort("修改密码失败！");
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable throwable) throws Exception {
                        T.showShort("修改密码失败！");
                        ErrorAction.print(throwable);
                    }
                });
    }
}
